﻿using Services.WXshopBuiness;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Model.WXshopBuiness;
using Model.WXshopBuiness.Enum;
using Model.WXshopBuiness.DTO;
using Core.WeiXin;
using System.Web.Script.Serialization;
using Xproject.Util;

namespace WeiXinProject.Controllers
{
    public class OrderController : WXBaseController
    {
        WXOrderServices m_WXOrderServices;
        AddressServices m_AddressServices;
        WXProductServices m_XProductServices;
        PromotionServices m_PromotionServices;
        public OrderController(WXOrderServices mWXOrderServices, AddressServices mAddressServices,WXProductServices wXProductServices, PromotionServices mPromotionServices)
        {
            m_WXOrderServices= mWXOrderServices;
            m_AddressServices = mAddressServices;
            m_XProductServices = wXProductServices;
            m_PromotionServices = mPromotionServices;
        }


        public ActionResult MyOrders(string type)
        {
            ViewBag.ordertype = type;
            return View();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Pay()
        {

            string orderID = Request.Form["orderID"];
            string addressId = Request.Form["addressId"];
            var jsonData = new Object();
            string result = string.Empty;             
            string userId = this.CurrentUser.UserID;
            WeiXinOrder order = m_WXOrderServices.GetDBOrderById(orderID); //先拿到订单信息
            if (order != null)
            {                                
                if(order.OrderState==(int)Enum_OrderState.WAITINGPAY){ //如果待支付， 
                    order.Remark = "微信支付开始！支付此订单";
                    order.AddressID = addressId;
                    OrderChangeHistory history = new OrderChangeHistory();
                    history.OrderId = order.OrderID;
                    history.OrderMoney = order.OrderMoney;
                    history.StateBefore = order.OrderState;
                    history.StateAfter = (int)Enum_OrderState.WAITINGPAY;
                    history.Remarks = "微信支付开始！订单变更 订单地址  订单状态待支付 ";                   
                    //拿商品信息
                    WXProduct product = m_XProductServices.GetById(order.ProductId);
                    decimal kanjia = 0.00M;
                    if (!string.IsNullOrEmpty(order.PromotionID))//如果有活动
                    {
                        Promotions p = m_PromotionServices.GetPromotionsById(order.PromotionID);
                        UserProductKanJia UPKJ = m_PromotionServices.CheckUserHasCreatedThisProductKanJia(p.PromotionID, order.ProductId, CurrentUser.UserID, orderID);
                        if (UPKJ != null)
                        {
                            kanjia = UPKJ.AleradKanJiaMoney;

                            List<PromotionsKanJiaDetail> details = m_PromotionServices.GetKJdetailList(UPKJ.KanJiaID);
                            decimal total = details.Select(i => i.KanJiaMoney).Sum();
                            if (total != kanjia)
                            {
                                jsonData = new { Success = false, Data = "砍价活动有异常，请联系平台客服" };
                                LogHelper.WriteInfoLog("此订单 砍价活动的 砍价统计和实际砍价流水 不一致，可能有非法篡改嫌疑，orderid  " + orderID + " userid " + CurrentUser.UserID);
                                return Json(jsonData, JsonRequestBehavior.AllowGet);
                            }
                        }
                    }
                    bool isBaoYou = false;
                    decimal defaultkdf = GetProductKDF(product, out isBaoYou);
                    order.NeedToPay = (order.OrderMoney) + defaultkdf - kanjia;
                    if (!isBaoYou)
                    {
                        order.KDMoney = defaultkdf;
                    }
                    history.OrderMoney = order.NeedToPay;
                    if (!m_WXOrderServices.UpdateDBOrderInfo(order, history))
                    {
                        jsonData = new { Success = false, Data = "更新订单状态失败" };

                        LogHelper.WriteInfoLog("更新订单状态失败 OrderController Pay :param :orderId " + orderID + " addressId " + addressId);
                        return Json(jsonData, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        jsonData = new { Success = true, Data = "下一步选择支付方式", OrderId = orderID };
                        Cache_UserInfoModel.Clear(userId);
                        LogHelper.WriteInfoLog("重新开始支付此订单 OrderController Pay :param :orderId " + orderID + " addressId " + addressId);
                        return Json(jsonData, JsonRequestBehavior.AllowGet);
                    }                 
                }

            }
            else
            {
                jsonData = new { Success = false, Data = "没有此订单信息" };
                LogHelper.WriteInfoLog("没有此订单信息 OrderController Pay :param :orderId " + orderID + " addressId " + addressId);
                return Json(jsonData, JsonRequestBehavior.AllowGet);
            }

            return null;
        }

        /// <summary>
        /// 取产品的快递费
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="isBaoYou"></param>
        /// <returns></returns>
        private decimal GetProductKDF(string productId,out bool isBaoYou)
        {
            isBaoYou = false;
            //系统默认的快递费
            string defasyskdf =CommonHelper.GetAppSettings("Default_kdf")??"10.00";
            decimal defaultkdf = decimal.Parse(defasyskdf);
            WXProduct product = m_XProductServices.GetById(productId);
            if (product.IsFreeShipping == 1)
            {
                isBaoYou = true;
                defaultkdf = 0.00M;
            }
            if (!isBaoYou)
            {
                //如果产品配置了快递费
                WeiXinProductAttrShowModel KDFattr = m_XProductServices.GetProductDefaultKDF(productId);
                if (KDFattr != null)
                {
                    decimal.TryParse(KDFattr.AttrValue, out defaultkdf);
                }
            }
            return defaultkdf;
        }

        private decimal GetProductKDF(WXProduct product, out bool isBaoYou)
        {
            isBaoYou = false;
            //系统默认的快递费
            string defasyskdf = CommonHelper.GetAppSettings("Default_kdf") ?? "10.00";
            decimal defaultkdf = decimal.Parse(defasyskdf);
            if (product.IsFreeShipping == 1)
            {
                isBaoYou = true;
                defaultkdf = 0.00M;
            }
            if (!isBaoYou)
            {
                //如果产品配置了快递费
                WeiXinProductAttrShowModel KDFattr = m_XProductServices.GetProductDefaultKDF(product.ProductID);
                if (KDFattr != null)
                {
                    decimal.TryParse(KDFattr.AttrValue, out defaultkdf);
                }
            }
            return defaultkdf;
        }

        public ActionResult PayOrderDetail(string orderId)
        {
            ViewBag.orderId = orderId;
            ViewBag.AddressID = string.Empty;
            ViewBag.HasKanJia = false;
            bool IsBaoYou = false;
            ViewBag.UserSpeciPrice = false;
            OrderInfoModel order =  m_WXOrderServices.GetOrderById(orderId);
            if (!string.IsNullOrEmpty(order.ProductSpecificationId))
            {
                ViewBag.UserSpeciPrice = true;
            }
            List<Address> myaddress = new List<Address>();
            Address DefaultAddress = null;
            decimal defaultkdf = 0.00M;
            
                        
            if (order != null)
            {
               myaddress = m_AddressServices.GetMyAddress(order.UserID);
                if (myaddress != null && myaddress.Count > 0)
                {
                    DefaultAddress = myaddress.Where(i =>i.IsDefault==1).FirstOrDefault();
                    if (DefaultAddress == null)
                    {
                        DefaultAddress = myaddress.FirstOrDefault();
                    }
                }
                defaultkdf = GetProductKDF(order.ProductId, out IsBaoYou);               
                ViewBag.AddressID = DefaultAddress!=null? DefaultAddress.AddressID:"";                
                if (!string.IsNullOrEmpty(order.PromotionID))//如果有活动
                {
                    Promotions p = m_PromotionServices.GetPromotionsById(order.PromotionID);
                    if (p != null)
                    {
                        UserProductKanJia UPKJ = m_PromotionServices.CheckUserHasCreatedThisProductKanJia(p.PromotionID, order.ProductId, CurrentUser.UserID, orderId);
                        if (UPKJ != null)
                        {
                            ViewBag.HasKanJia = true;
                            ViewData["userKanJiaInfo"] = UPKJ;
                        }
                    }

                }
            }
            // 在这里检测是否有砍价活动
           
          
               
             //如果有的话，那么要把这个砍价活动砍来的价格都算到折扣里去
             //页面加一个 砍价折扣优惠行                         

            //得到所有的收货地址
            ViewData["Address"] = myaddress;
            ViewData["DefaultAddress"] = DefaultAddress;
            ViewData["DefaultKDF"]= defaultkdf;
            ViewBag.IsBaoYou = IsBaoYou;
            return View(order);
        }

        public JsonResult ConfrimReceipeOrder()
        {
            var jsonData = new Object();
            string result = string.Empty;
           
            string orderId = Request.Form["orderId"];
            WeiXinOrder order = m_WXOrderServices.GetById(orderId);
            if (order == null)
            {
                jsonData = new { Success = false, Data = "产品不存在" };
                return Json(jsonData, JsonRequestBehavior.AllowGet);
            }

            //变更订单状态
            OrderChangeHistory history = new OrderChangeHistory();
            history.OrderId = order.OrderID;
            history.OrderMoney = order.OrderMoney;
            history.StateBefore = order.OrderState;
            history.StateAfter = (int)Enum_OrderState.WAITCOMMENT;
            history.Remarks = "订单已确认收货！";
            order.OrderState = (int)Enum_OrderState.WAITCOMMENT;
            if (!m_WXOrderServices.UpdateDBOrderInfo(order, history))
            {
                jsonData = new { Success = false, Data = "更新订单状态失败" };

                LogHelper.WriteInfoLog("更新订单状态失败 OrderController Pay :param :orderId " + order.OrderID);
                return Json(jsonData, JsonRequestBehavior.AllowGet);
            }
            else {
                jsonData = new { Success = true, Data = "订单已确认收货，赶快去给个评价吧！" };
            }

            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        public ActionResult PaySelect(string orderId)
        {
            WeiXinOrder order = m_WXOrderServices.GetDBOrderById(orderId);
            try
            {             
                ViewBag.Price = 0;
                ViewBag.RealPrice = 0;
                ViewBag.wxJsApiParam = "null";
                decimal orderPrice = 0.00M;               
                if (order != null)
                {
                    ViewBag.Price =  orderPrice;
                    ViewBag.RealPrice =orderPrice;
                    ViewBag.wxJsApiParam = "null";
                    //进行微信的预支付
                    //这儿做账号是否被锁啊，能不能支付的与判断
                    if (true)
                    {
                        //拿商品信息
                        WXProduct product = m_XProductServices.GetById(order.ProductId);
                        decimal kanjia = 0.00M;
                        
                        if (!string.IsNullOrEmpty(order.PromotionID))//如果有活动
                        {
                            Promotions p = m_PromotionServices.GetPromotionsById(order.PromotionID);
                            if (p != null)
                            {
                                UserProductKanJia UPKJ = m_PromotionServices.CheckUserHasCreatedThisProductKanJia(p.PromotionID, order.ProductId, CurrentUser.UserID, orderId);
                                if (UPKJ != null)
                                {
                                    kanjia = UPKJ.AleradKanJiaMoney;
                                    List<PromotionsKanJiaDetail> details = m_PromotionServices.GetKJdetailList(UPKJ.KanJiaID);
                                    decimal total = details.Select(i => i.KanJiaMoney).Sum();
                                    if (total != kanjia)
                                    {
                                        LogHelper.WriteInfoLog("此订单 砍价活动的 砍价统计和实际砍价流水 不一致，可能有非法篡改嫌疑，orderid  " + orderId + " userid " + CurrentUser.UserID);
                                    }
                                }
                            }
                            
                        }                                               
                       
                        bool isBaoYou = false;
                        decimal defaultkdf = GetProductKDF(product, out isBaoYou);
                        order.NeedToPay = (order.OrderMoney) + defaultkdf - kanjia;
                        if (!isBaoYou)
                        {
                            order.KDMoney = defaultkdf;
                        }                        
                        OrderChangeHistory history3 = new OrderChangeHistory();
                        history3.OrderId = order.OrderID;
                        history3.StateBefore = order.OrderState;
                        history3.StateAfter = (int)Enum_OrderState.WAITINGPAY;
                        history3.Remarks = "微信支付开始！";
                        history3.OrderMoney = order.OrderMoney;
                        if (m_WXOrderServices.UpdateDBOrderInfo(order, history3))
                        {
                            //调用微信 支付接口 预支付
                            //attach 这儿写死 jsad78sadmASB2chenqiang 微信支付完毕，微信通知回完整返回此attach
                            //或者可以 动态 每个订单有个attach 数据库查询出来比对
                            WeiXinModel.WxJsApiParam model = WeiXinHelper.Pay(order.OrderID, this.CurrentUser.UserID, this.CurrentUser.OpenId, order.NeedToPay, "", CommonHelper.GetAppSettings("MessageSender") + "-"+ "线上商超", "jsad78sadmASB2chenqiang", CommonHelper.GetAppSettings("MessageSender") + "-"+product.ProductName,
                            "JSAPI", "用户订单支付");
                            ViewBag.wxJsApiParam = new JavaScriptSerializer().Serialize(model);
                        }
                        else
                        {
                            LogHelper.WriteInfoLog("开始支付此订单出现异常 OrderController Pay :param :orderId " + orderId );
                        }
                           
                    }
                }
            }
            catch (Exception ex)
            {
                //写日志
                LogHelper.WriteErrorLog("微信预支付出错 OrderController--PaySelect :param: orderId = "+ orderId, ex);
            }            
            return View(order);
        }

        public JsonResult partialMyShopCarList(int? index, int? pagesize)
        {
            var jsonData = new Object();
            List<ShoppingCar> model = new List<ShoppingCar>();            
            int total = 0;
            model = m_WXOrderServices.GetUserShoppingCarList(base.CurrentUser.UserID, pagesize, index, out total);                       
            jsonData = new { Success = true, Data = model };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        public JsonResult partialMyOrderList(string  type,int? index, int? pagesize)
        {
            var jsonData = new Object();
            List<OrderInfoModel> model = new List<OrderInfoModel>();
            if (!string.IsNullOrEmpty(type) && type == "all")
            {
                int total = 0;
                model = m_WXOrderServices.GetUserAllOrderDetailList(base.CurrentUser.UserID, pagesize, index, out total);
            }
            else {
                int total = 0;
                int itype = 0;
 
                int.TryParse(type,out itype); 
                model = m_WXOrderServices.GetUserOrderDetailList(base.CurrentUser.UserID, itype, pagesize, index, out total);

            }

            jsonData = new { Success = true, Data = model };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public JsonResult AddToShoppingCartNew()
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            string userId = this.CurrentUser.UserID;
            //先拿到产品信息
            string productId = Request.Form["productId"];
            int productNum = 1;
            string nums = Request.Form["Nums"];
            int.TryParse(nums, out productNum);
            string specifationId = Request.Form["specifationId"];
            List<ProductSpecification> specis = m_XProductServices.GetProductSpecList(productId);
            if (specis != null && specis.Count>0)
            {
                if (string.IsNullOrEmpty(specifationId))
                {
                    jsonData = new { Success = false, Data = "请选择规格"};
                    return Json(jsonData, JsonRequestBehavior.AllowGet);
                }
            }

            ShoppingCar shopcar =  m_WXOrderServices.GetUserProductInCar(userId, productId, specifationId,0);
            if (shopcar != null)//如果已存在，那么就是加数量就是，
            {
                WXProduct product = m_XProductServices.GetById(productId);
                decimal saleprice = product.SalePrice;
                decimal marketprice = product.MarketPrice;
                if(specis != null && specis.Count > 0)
                {
                    if (!string.IsNullOrEmpty(specifationId))
                    {
                        ProductSpecification ps = m_XProductServices.GetProdSpecById(specifationId);
                        saleprice = ps.SalesPrice;
                        marketprice = ps.OrignPrice;
                    }
                }
                success = m_WXOrderServices.UpdateUserShoppingCarNumsAndPrice(shopcar,saleprice,marketprice,productNum);
                if (success)
                {
                    int total = m_WXOrderServices.GetUserShoppingCarCount(userId);
                    decimal topay = m_WXOrderServices.GetUserShoppingCarMoney(userId);
                    Cache_UserInfoModel.Clear(userId);
                    jsonData = new { Success = success, Data =   "已成功添加到购物车", totallist = total, toPay = topay.ToString("#0.00") };
                }
                else
                {
                    jsonData = new { Success = success, Data = "添加失败了！请重试" };
                }


            }
            else {
                WXProduct product = m_XProductServices.GetById(productId);
                if (product == null)
                {
                    jsonData = new { Success = true, Data = "产品不存在" };
                    return Json(jsonData, JsonRequestBehavior.AllowGet);
                }
                if (product.State == 1) {
                    jsonData = new { Success = true, Data = "产品已下架" };
                    return Json(jsonData, JsonRequestBehavior.AllowGet);
                }
                if (product.State == 2)
                {
                    jsonData = new { Success = true, Data = "产品已过期" };
                    return Json(jsonData, JsonRequestBehavior.AllowGet);
                }
                shopcar = new ShoppingCar();
                ProductSpecification specifation = m_XProductServices.GetProductSpecification(specifationId);
                success= m_WXOrderServices.AddToShopingCar(shopcar, product, specifation, userId, productNum,
                    GetDomain+ "/Shop/ProductDetail?productId="+product.ProductID,
                    "用户添加到购物车 ：pcode:"+product.ProductCode+"pcategory:"+product.CategoryID);
                if (success)
                {
                    int total = m_WXOrderServices.GetUserShoppingCarCount(userId);
                    decimal topay = m_WXOrderServices.GetUserShoppingCarMoney(userId);
                    Cache_UserInfoModel.Clear(userId);                    
                    jsonData = new { Success = success, Data = "已成功添加到购物车", totallist = total, toPay = topay.ToString("#0.00") };
                }
                else
                {
                    jsonData = new { Success = success, Data = "添加失败了！请重试" };
                }


            }            
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public JsonResult ModifyShoppingCarNums()
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            string userId = this.CurrentUser.UserID;
            //先拿到产品信息
            string shopcarId = Request.Form["shopcarId"];
            int productNum = 1;            
            string type = Request.Form["type"];
            ShoppingCar shopcar = m_WXOrderServices.GetShoppingCarById(shopcarId);
            if (type == "redu")
            {
                productNum = -1;
                 
            }if (type == "plus")
            {
                productNum = 1;
            }
            if (shopcar != null&&productNum==-1)
            {
                if (shopcar.ProductNum <= 1)
                {
                    jsonData = new { Success = success, Data = "OK", Total = shopcar.StrSignlePrice };
                    return Json(jsonData, JsonRequestBehavior.AllowGet);
                }
            }
            WXProduct product = m_XProductServices.GetById(shopcar.ProductId);
            decimal saleprice = product.SalePrice;
            decimal marketprice = product.MarketPrice;
            if (!string.IsNullOrEmpty(shopcar.ProductSpecificationId))
            {
                ProductSpecification ps = m_XProductServices.GetProdSpecById(shopcar.ProductSpecificationId);
                saleprice = ps.SalesPrice;
                marketprice = ps.OrignPrice;
            }                       
            success = m_WXOrderServices.UpdateUserShoppingCarNumsAndPrice(shopcar, saleprice, marketprice, productNum);
            if (success)
            {
                Cache_UserInfoModel.Clear(this.CurrentUser.UserID);
                jsonData = new { Success = success, Data ="OK" ,Total = (shopcar.SinglePrice*(shopcar.ProductNum)).ToString("#0.00") };
            }
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        public JsonResult PayThisShopCar()
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            string userId = this.CurrentUser.UserID;
            string shopcarId = Request.Form["shopcarId"];
            ShoppingCar shopcar = m_WXOrderServices.GetShoppingCarById(shopcarId);
            WXProduct xProduct = new WXProduct();
            string OrderName = string.Empty;
            string orderId = string.Empty;
            if (shopcar == null)
            {
                jsonData = new { Success = false, Data = "产品不存在" };
                return Json(jsonData, JsonRequestBehavior.AllowGet);
            }
            else
            {
                xProduct = m_XProductServices.GetById(shopcar.ProductId);
                //检查是不是还有效，比如有些特价产品这样的，限时购的
                OrderName = xProduct.ProductName + xProduct.Spec1 + xProduct.Spec2 + xProduct.Spec3 + xProduct.Spec4 + xProduct.Spec5;
            }
            success = m_WXOrderServices.AddToOrder(shopcar,OrderName, userId, (shopcar.SinglePrice)*shopcar.ProductNum, shopcar.ProductNum, shopcar.ProductId,
                "加入购物车", 0, 0, 0, 0, 1,out orderId);
            result = success ? "下一步：订单确认" : "添加失败";
            if (success)
            {             
                Cache_UserInfoModel.Clear(userId);
                jsonData = new { Success = success, Data = result, orderId = orderId };
            }
            else {
                jsonData = new { Success = success, Data = result};
            }
           

            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
        public JsonResult DelThisShopCarId()
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;

            string shopcarId = Request.Form["shopcarId"];
            ShoppingCar shopcar = m_WXOrderServices.GetShoppingCarById(shopcarId);
            if (shopcar == null)
            {
                jsonData = new { Success = false, Data = "购物车不存在此项" };
                return Json(jsonData, JsonRequestBehavior.AllowGet);
            }            
            success = m_WXOrderServices.DelShopCar(shopcar);
            if (success)
            {
                jsonData = new { Success = true, Data = "已成功删除~" };
                Cache_UserInfoModel.Clear(this.CurrentUser.UserID);
            }
            else
            {
                jsonData = new { Success = false, Data = "删除失败~" };
                LogHelper.WriteInfoLog("用户手动订单删除失败！ shopcar " + shopcarId);
            }

            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
        public JsonResult AddToShoppingCartOld(string productId,decimal ordermoney)
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            string userId = this.CurrentUser.UserID;
            WXProduct xProduct = m_XProductServices.GetById(productId);
            string OrderName = string.Empty;
            string orderId = string.Empty;
            if (xProduct == null)
            {
                jsonData = new { Success = false, Data = "产品不存在" };
                return Json(jsonData, JsonRequestBehavior.AllowGet);
            }
            else {
                //to do 
                //检查是不是还有效，比如有些特价产品这样的，限时购的
                OrderName = xProduct.ProductName + xProduct.Spec1 + xProduct.Spec2 + xProduct.Spec3 + xProduct.Spec4 + xProduct.Spec5;
            }
            success =  m_WXOrderServices.AddToShoppingCartOld(OrderName, userId, xProduct.SalePrice, productId, "加入购物车", 0, 0, 0, 0, 1);
            result = success ? "添加成功" : "添加失败";
            
            List<WeiXinOrder> orders =  m_WXOrderServices.GetUserOrderList(userId, (int)Enum_OrderState.SHOPCAR);
            string liststr = orders.Count.ToString();
            string toPaystr = orders.Select(m => m.OrderMoney).Sum().ToString("#0.00");
            Cache_UserInfoModel.Clear(userId);
            jsonData = new { Success = success, Data = result ,totallist= liststr, toPay = toPaystr };
            
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        public ActionResult ProductComment(string orderId)
        {
            if (string.IsNullOrEmpty(orderId))
            {
                return View("~/UserCenter/UserCenter");
            }
            WeiXinOrder order = m_WXOrderServices.GetById(orderId);
            ProductComments comments = m_XProductServices.GetMyComments(orderId,order.ProductId, this.CurrentUser.UserID);
            ViewBag.productId = order.ProductId;
            ViewBag.orderId = orderId;
            if (comments != null)
            {
                ViewBag.DoneBfore = true;
                return View(comments);

            }else
            {
                ViewBag.DoneBfore = false;
                return View();
            }   
        }
       
        [HttpPost]
        public JsonResult DoComments()
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            string CommentServiceStarts = Request["CommentServiceStarts"];
            string CommentLogisticStarts = Request["CommentLogisticStarts"];
            string CommentPackageStarts = Request["CommentPackageStarts"];
            string Comments = Request["Comments"];
            string productId = Request["productId"];
            string OrderId = Request["OrderId"];
            if (string.IsNullOrEmpty(productId) || string.IsNullOrEmpty(OrderId))
            {
                result = "参数错误！";
                jsonData = new { Success = success, Data = result };

                return Json(jsonData, JsonRequestBehavior.AllowGet);
            }
            ProductComments comments = new ProductComments();            

            comments.CommentServiceStarts = int.Parse(CommentServiceStarts);
            comments.CommentLogisticStarts = int.Parse(CommentLogisticStarts);
            comments.CommentPackageStarts = int.Parse(CommentPackageStarts);
            comments.CommentTotalStarts =( comments.CommentServiceStarts + comments.CommentLogisticStarts + comments.CommentPackageStarts)/3;
            comments.Comment = Comments;
            comments.CommentIndex = 1;
            comments.CreateTime = DateTime.Now;
            comments.Enable = 1;
            comments.ID = Guid.NewGuid().ToString();
            comments.UserId = this.CurrentUser.UserID;
            comments.UserImgUrl = this.CurrentUser.HeadUrl;
            comments.UserName = this.CurrentUser.NickName;
            comments.OrderId = OrderId;

            WXProduct product = m_XProductServices.GetById(productId);
            comments.ProductCode = product.ProductCode;
            comments.ProductName = product.ProductName;
            comments.ProductID = productId;
            success = m_XProductServices.InsertProductComments(comments);
            //变更订单状态
            OrderChangeHistory history = new OrderChangeHistory();
            WeiXinOrder order = m_WXOrderServices.GetById(OrderId);
            history.OrderId = order.OrderID;
            history.OrderMoney = order.OrderMoney;
            history.StateBefore = order.OrderState;
            history.StateAfter = (int)Enum_OrderState.FINISHED;
            history.Remarks = "订单添加评论！订单由 待评价-->已完成";
            order.OrderState = (int)Enum_OrderState.FINISHED;
            success =m_WXOrderServices.UpdateDBOrderInfo(order,history);
            result = success ? "评论成功！" : "评论失败！";
            jsonData = new { Success = success, Data = result };
            Cache_UserInfoModel.Clear(this.CurrentUser.UserID);
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        } 
        [HttpPost]
        public JsonResult DelThisOrder()
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
 
            string orderId= Request.Form["orderID"];
            WeiXinOrder order = m_WXOrderServices.GetById(orderId);
            if (order == null) { 
                jsonData = new { Success = false, Data = "产品不存在" };
                return Json(jsonData, JsonRequestBehavior.AllowGet);
            }

            //变更订单状态
            OrderChangeHistory history = new OrderChangeHistory(); 
            history.OrderId = order.OrderID;
            history.OrderMoney = order.OrderMoney;
            history.StateBefore = order.OrderState;
            history.StateAfter = (int)Enum_OrderState.DELETE;
            history.Remarks = "订单被用户手动删除！订单 -->已删除";
            success = m_WXOrderServices.DelOrder(order, history);
          
            if (success)
            {
                UserProductKanJia upkj= m_PromotionServices.CheckUserHasCreatedThisProductKanJia(order.PromotionID, order.ProductId, CurrentUser.UserID, orderId);
                if (upkj != null)
                {
                    //如果有参与砍价活动，费除掉这个砍价活动
                    m_PromotionServices.UpdateUserProductKanJiaState(upkj,1);
                }
                jsonData = new { Success = true, Data = "订订已成功删除~" };
            }
 
            else {
 
                jsonData = new { Success = false, Data = "订订删除失败~" };
                LogHelper.WriteInfoLog("用户手动订单删除失败！ orderid " + orderId);
            }

            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
 
    }
}